<template>
  <a-modal
    :title="isShow ? '修改用户' : '新建用户'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
    okText="确定"
    cancelText="取消"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show = "false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="业务员">
          <a-input v-decorator="['name', {rules: [{required: true, message: '用户名必须填写'}]}]" />
        </a-form-item>
        <!-- <a-form-item v-if="model == null" label="密码">
          <a-input v-decorator="['password',  {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}]}]" />
        </a-form-item> -->
        <a-form-item label="联系人">
          <a-input v-decorator="['lian', {rules: [{required: true, message: '请输入联系人'}]}]" />
        </a-form-item>

        <a-form-item label="上传头像">
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="$api.upload"
            :before-upload="beforeUpload"
            @change="handleLogoChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
              <a-icon :type="loadings ? 'loadings' : 'plus'" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
        </a-form-item>

        <a-form-item label="手机号">
          <a-input v-decorator="['mobile', {rules: [{required: true, min: 11, message: '请输入至少五个字符的规则描述！'}]}]" />
        </a-form-item>

        <a-form-item label="地址">
          <a-input v-decorator="['area', {rules: [{required: true, min: 2, message: '请输入至少五个字符的规则描述！'}]}]" />
        </a-form-item>

        <a-form-item label="营业时间">
          <a-input v-decorator="['cTime', {rules: [{required: true, min: 2, message: '请输入至少五个字符的规则描述！'}]}]" 
          placeholder="00-00 格式"
          />
        </a-form-item>

        <a-form-item label="预约时间">
          <a-input v-decorator="['yTIme', {rules: [{required: true, min: 2, message: '请输入至少五个字符的规则描述！'}]}]" 
          placeholder="00-00 格式"
          />
        </a-form-item>
        <!-- <a-form-item label="性别">
          <a-select v-decorator="['sex', {rules: [{required: true, message: '请选择性别'}]}]" placeholder="请选择性别">
            <a-select-option :value="1">男</a-select-option>
            <a-select-option :value="2">女</a-select-option>
          </a-select>
        </a-form-item> -->
        <!-- <a-form-item label="角色名称">
          <a-select
            v-decorator="['role_id', {rules: [{required: true, message: '请选择角色'}]}]" 
            show-search
            placeholder="请选择角色"
            option-filter-prop="children"
            :filter-option="filterOption"
          >
            <a-select-option :value="item.id" v-for="(item) in roleList" :key="item.id">
                {{item.name}}
            </a-select-option>
          </a-select>
        </a-form-item> -->
        <!-- <a-form-item label="部门名称">
          <a-select
            v-decorator="['department_id']"
            show-search
            placeholder="请选择部门"
            option-filter-prop="children"
            :filter-option="filterOption"
          >
            <a-select-option :value="item.id" v-for="(item) in department" :key="item.id">
                {{item.name}}
            </a-select-option>
          </a-select>
        </a-form-item> -->

        <!-- <a-form-item label="校区">
          <a-select
            v-decorator="['campus_id', {rules: [{required: true, message: '请选择校区'}]}]"
            show-search
            placeholder="请选择校区"
            option-filter-prop="children"
            :filter-option="filterOption"
            @change="campusChange"
          >
            <a-select-option :value="item.id" v-for="(item) in getCampusList" :key="item.id">
                {{item.name}}
            </a-select-option>
          </a-select>
        </a-form-item> -->

        <!-- <a-form-item label="数据权限">
          <a-select v-decorator="['type', {rules: [{required: true, message: '请选择数据权限'}]}]" placeholder="请选择数据权限">
            <a-select-option :value="1">校区人员</a-select-option>
            <a-select-option :value="2">后台管理人员</a-select-option>
          </a-select>
        </a-form-item> -->

        <!-- <a-form-item label="是否为志愿者">
          <a-select v-decorator="['volunteer']" placeholder="请选择是否志愿者">
            <a-select-option :value="1">不是</a-select-option>
            <a-select-option :value="2">是</a-select-option>
          </a-select>
        </a-form-item> -->
        
        <!-- <a-form-item label="是否为教师">
          <a-select v-decorator="['teacher']" placeholder="请选择为教师">
            <a-select-option :value="1">不是</a-select-option>
            <a-select-option :value="2">是</a-select-option>
          </a-select>
        </a-form-item> -->

        <!-- <a-form-item label="简介">
          <a-textarea v-decorator="['introduction']"></a-textarea>
        </a-form-item> -->

        <!-- <a-form-item label="备注">
          <a-textarea v-decorator="['remark']"></a-textarea>
        </a-form-item> -->

      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'

// 引入角色列表
import { getRoLeList } from '../../../../api/system'
// 表单字段
// const fields = ['id', 'username','name', 'sex', 'role_id', 'department_id', 'mobile', 'campus_id', 'volunteer', 'teacher', 'remark', 'introduction']
const fields = ['id', 'name','lian', 'avatar', 'mobile', 
'area', 'startTime', 'cTime', 'yTIme']
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      // 判断是否未分校
      is_fen: false,
      // 校区列表
      // 图片
      loadings: false,
      imageUrl: '',
      isShow: false,
      // 部门列表
      department: [],
      // 角色列表
      roleList: [],
      form: this.$form.createForm(this)
    }
  },
  created () {
    if(localStorage.getItem('user_type') != 2) {
      this.is_fen = true
    }
    // 调用方法获取校区列表
    //this.getgetCampusList()
    // 调用方法获取角色列表
    //this.UsersGetRoLeList ()
    // 调用方法获取部门列表
    //this.UsergetDepartmentList()

    console.log('custom modal created')

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      if(this.model && this.model.id > 0) {
        this.isShow = true
        this.imageUrl =  this.model.avatar
      } else {
        this.isShow = false
        this.imageUrl = ''
      }
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  methods: {
    /**
     * 当总校区时 返回2
     * 其他非总校区 返回1
     */
    campusChange(value, option) {
        let Campus = this.getCampusList.filter(item => {
        if(item.name == '总校区' && item.id == value) {
          return item
        } else {
          return null
        }
      })
      if(Campus.length > 0) {
        this.$emit('campus', 2)
      } else {
        this.$emit('campus', 1)
      }
    },
    handleLogoChange(info) {
      console.log('------------info----------', info)
      if (info.file.status === 'uploading') {
        this.loadings = true;
        return;
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          console.log('--------------logo---------------', info.file.response.data.url)
          this.imageUrl = imageUrl;
          this.loadings = false;
          this.$emit('getImage', info.file.response.data.url)
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!');
      }
      return isJpgOrPng && isLt2M;
    },
    // 获取校区列表
    getgetCampusList() {
      getCampus().then(res => {
        if(this.is_fen) {
          this.getCampusList = res.data.data.filter(item => {
            if(item.name != '总校区'){
              return item
            }
          }) 
        } else {
        console.log(res.data.data)
          this.getCampusList = res.data.data
        }
      })
    },
    // 获取角色列表
    UsersGetRoLeList () {
      getRoLeList().then(res => {
        this.roleList = res.data.data
      })
    },
    // 获取部门列表
    UsergetDepartmentList () {
      getDepartmentList().then(res => {
        const value = res.data.data.filter(item => {
          return item.status != 2
        })
        this.department = value
      })
    },
    // 搜素模糊查询
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      }
  }
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.avatar-uploader img {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>

